from fastapi import FastAPI, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from typing import List

from database import get_db, engine
from models import Base, User
from schemas import UserCreate, UserUpdate, User as UserSchema
from crud import get_user, get_users, create_user, update_user, delete_user

# 创建数据库表
Base.metadata.create_all(bind=engine)

app = FastAPI()

# 创建用户
@app.post("/users/", response_model=UserSchema, status_code=status.HTTP_201_CREATED)
def create_user_endpoint(
    user: UserCreate, 
	db: Session = Depends(get_db)
):
    db_user = create_user(db, user)
    if not db_user:
        raise HTTPException(status_code=400, detail="Email already registered")
    return db_user

# 获取所有用户
@app.get("/users/", response_model=List[UserSchema])
def read_users(
    skip: int = Query(0, ge=0, description="跳过记录数"),
    limit: int = Query(100, ge=1, le=1000, description="每页记录数"),
	db: Session = Depends(get_db)
):
    users = get_users(db, skip=skip, limit=limit)
    return users

# 获取单个用户
@app.get("/users/{user_id}", response_model=UserSchema)
def read_user(
    user_id: int, 
	db: Session = Depends(get_db)
):
    db_user = get_user(db, user_id=user_id)
    if db_user is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="User not found"
        )
    return db_user

# 更新用户
@app.put("/users/{user_id}", response_model=UserSchema)
def update_user_endpoint(
    user_id: int,
	user: UserUpdate,
	db: Session = Depends(get_db)
):
    db_user = update_user(db, user_id=user_id, user=user)
    if db_user is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="User not found"
        )
    return db_user

# 删除用户
@app.delete("/users/{user_id}", response_model=UserSchema)
def delete_user_endpoint(
    user_id: int, 
    db: Session = Depends(get_db)
):
    db_user = delete_user(db, user_id=user_id)
    if db_user is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="User not found"
        )
    return db_user

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)